// src/screens/RegisterScreen.js
import React, { useState } from 'react';
import { View, TextInput, Button, Text, Alert, TouchableOpacity, StyleSheet, Platform } from 'react-native';
import api from '../services/api';
import { useDispatch } from 'react-redux';
import { setUserInfo } from '../store/userSlice';

const RegisterScreen = ({ navigation }) => {
  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const dispatch = useDispatch();

  const handleRegister = async () => {
    if (!name || !phone || !password || !confirmPassword) {
      Alert.alert('错误', '请填写所有字段');
      return;
    }

    if (password !== confirmPassword) {
      Alert.alert('错误', '密码和确认密码不匹配');
      return;
    }

    if (password.length < 6) {
      Alert.alert('错误', '密码长度至少为6位');
      return;
    }

    setLoading(true);
    try {
      // 清理手机号，去除空格等不可见字符
      const cleanPhone = phone.trim();
      const response = await api.register(cleanPhone, password, name);
      
      if (response && response.access_token) {
        const token = response.access_token;
        // 设置API token
        api.setToken(token);
        // 获取当前用户信息
        const userResponse = await api.getCurrentUser();
        // 存储用户信息到Redux
        dispatch(setUserInfo({ token, user: userResponse }));
        // 跳转到主页
        navigation.replace('Main');
      } else {
        Alert.alert('注册失败', response?.message || '注册失败，请重试');
      }
    } catch (error) {
      console.log('注册出错:', error);
      if (error.response) {
        Alert.alert('注册失败', error.response.data?.message || '服务器错误');
      } else if (error.request) {
        Alert.alert('注册失败', '网络请求失败，请检查网络连接和服务器状态');
      } else {
        Alert.alert('注册失败', error.message || '未知错误');
      }
    } finally {
      setLoading(false);
    }
  };

  const handleGoogleRegister = async () => {
    Alert.alert('提示', 'Google注册功能将在后续版本中实现');
    // 这里需要实现Google注册逻辑
  };

  const handleFacebookRegister = async () => {
    Alert.alert('提示', 'Facebook注册功能将在后续版本中实现');
    // 这里需要实现Facebook注册逻辑
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>用户注册</Text>
      
      <TextInput
        placeholder="请输入姓名"
        value={name}
        onChangeText={setName}
        style={styles.input}
      />
      
      <TextInput
        placeholder="请输入手机号"
        value={phone}
        onChangeText={setPhone}
        keyboardType="phone-pad"
        style={styles.input}
      />
      
      <TextInput
        placeholder="请输入密码"
        secureTextEntry
        value={password}
        onChangeText={setPassword}
        style={styles.input}
      />
      
      <TextInput
        placeholder="请确认密码"
        secureTextEntry
        value={confirmPassword}
        onChangeText={setConfirmPassword}
        style={styles.input}
      />
      
      <Button 
        title={loading ? "注册中..." : "注册"} 
        onPress={handleRegister} 
        disabled={loading}
      />

      {Platform.OS === 'android' && (
        <View style={styles.socialLoginContainer}>
          <Button 
            title="使用Google注册" 
            onPress={handleGoogleRegister} 
            color="#4285F4"
          />
          <Button 
            title="使用Facebook注册" 
            onPress={handleFacebookRegister} 
            color="#4267B2"
          />
        </View>
      )}
      
      <View style={styles.footer}>
        <Text>已有账号？</Text>
        <TouchableOpacity onPress={() => navigation.navigate('Login')}>
          <Text style={styles.link}>立即登录</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    padding: 20,
    flex: 1,
    justifyContent: 'center'
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    textAlign: 'center',
    marginBottom: 30
  },
  input: {
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 5,
    padding: 10,
    marginBottom: 15
  },
  socialLoginContainer: {
    marginVertical: 10,
  },
  footer: {
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: 20
  },
  link: {
    color: 'blue',
    marginLeft: 5
  }
});

export default RegisterScreen;